package com.string;

import java.util.ArrayList;
import java.util.List;

/**04-18
 * 分割回文串
 * 递归+回溯+动态规划
 */
public class Partition131 {
    int[][] dp;
    public List<List<String>> partition(String s) {
        int len=s.length();
        List<List<String>> res = new ArrayList<>();
        if (s==null||len==0){
            return res;
        }
        //保存子串的状态 ，1是回文 ，2不是
        dp=new int[len][len];
        for (int i = 0; i < len; i++) {
            dp[i][i]=1;
        }
        backTrack(s,0,len,new ArrayList<String>(),res);

        return res;
    }

    private void backTrack(String s, int start, int len, ArrayList<String> tempList, List<List<String>> res) {
        if (start==len){
            res.add(new ArrayList<String>(tempList));
        }

        for (int i = start; i < len; i++) {
            if (!check(s,start,i)){
                continue;
            }
            tempList.add(s.substring(start,i+1));
            backTrack(s, i+1, len, tempList, res);

            tempList.remove(tempList.size()-1);
        }

    }
    //利用左右指针 判断是否为回文串，
    private boolean check(String s, int left, int right) {
        if (dp[left][right]==1){
            return true;
        }else if (dp[left][right]==2){
            return false;
        }else {
            while (left<right){
                if (s.charAt(left)!=s.charAt(right)){
                    dp[left][right]=2;
                    return false;
                }
                left++;
                right--;
            }
            dp[left][right]=1;
            return true;
        }
    }
}
